from actions.action import Action
from util import remove_clicked_item, get_item
from logger import logger


class NormalProAction(Action):

    def check(self, activity, config, driver):
        # 当前页面返回的控件
        normal_dict = activity.elements

        if not hasattr(activity, "normal_clicked"):
            activity.normal_clicked = {}

        self.need_to_click = {}
        for el, ac in activity.next:
            if hasattr(ac, "normal_all_clicked") and ac.normal_all_clicked:
                logger.info("next activity pass: {}".format(ac))
                continue

            logger.info("next activity need to: {}".format(ac))
            if el is not None and el.key() in normal_dict:  # 当前页面中存在
                self.need_to_click[el.key()] = el

        # normal_dict中,要剔除已经被点过的控件
        remove_clicked_item(activity.normal_clicked, normal_dict)
        length = len(normal_dict)

        logger.info("normal_dict: {}".format(normal_dict))

        if length > 0:
            activity.normal_dict = normal_dict
            activity.normal_all_clicked = False
            return True
        elif length == 0:
            activity.normal_all_clicked = True
            return False

    def run(self, activity, config, driver):
        if self.need_to_click:
            logger.info("need_to_click: {}".format(self.need_to_click))
            value = get_item(self.need_to_click, activity.normal_clicked)
        else:
            logger.info("normal_dict:{}".format(activity.normal_dict))
            normal_dict = activity.normal_dict
            value = get_item(normal_dict, activity.normal_clicked)

        if value is not None:
            activity.element = value
            activity.action = "click"

    def run_next_acton(self):
        return False
